import {Component, ViewEncapsulation, ViewChild, Output, EventEmitter, Input} from '@angular/core';
import {UserService} from '../../../../services/app.user';
import {BaThemeSpinner}  from '../../../../theme/services';
import {Utility} from '../../../../services/app.utility';
import {UserProfile} from '../../../shared/profile/profile.component';
import {IdeaService} from '../../../../services/app.idea';
import {Modal} from 'ngx-modal/Modal';
import {viewCardIdeaDetail} from '../../../shared/ideas/component/viewCardIdeaDetail/viewCardIdeaDetail.component';
import {Constants} from '../../../../common/app.constants';
declare let toastr:any;
declare let $:any;

@Component({
    selector: 'AbuseList',
    encapsulation: ViewEncapsulation.None,
    templateUrl: './abuseList.html',
    styleUrls: ['./abuseList.scss']
})

export class AbuseList {
    @Input()
    constants:Constants;
    @ViewChild(UserProfile)
    profile:UserProfile;
    @ViewChild('ViewDetailIdeaModel')
    public ViewDetailIdeaModel:Modal;
    @Output()
    notifyParent:EventEmitter<any> = new EventEmitter();
    @ViewChild(viewCardIdeaDetail)
    viewCardIdeaDetail:viewCardIdeaDetail;
    @ViewChild('abuseModal')
    public abuseModal:Modal;
    @ViewChild('Modal')
    public UserProfileModal:Modal;
    allusers:Array<any>;
    myDatePickerOptions:any;
    fromDate:string;
    toDate:string;
    public category:any;
    public searchType:any;
    public usersPage:any;
    public listOfUsers:any = [];
    public checkedStatus:any;
    public dateFormat:any;
    public totalItem:number;
    public currentPage:number = 1;
    public itemPerPage:number = 10;
    public firstReason:any;
    public secondReason:any;
    public thirdReason:any;
    public forthReason:any;
    public commentListOfIdea:any;
    public spamModal:any;
    public spamResult:any;
    public spamReason:any;
    public allSpam:any;
    public noContent:boolean;
    public start:any;
    public end:any;
    public check:any;
    public date:any;
    public downIcon:boolean;
    public commentAddedFlag:boolean;
    public inputTag:any;
    public userName:any;
    public listOfUsersTemplate:any;
    public userprofile:any;
    public userModal:any;
    public selectTag:any;
    public abuseIdea:any;
    public viewDetailIdea:any;
    public updateUser:any;


    constructor(private userService:UserService, private ideaService:IdeaService, private spinner:BaThemeSpinner, private utility:Utility) {
        this.constants = new Constants();
        // added code for filter
        this.date = true;
        this.noContent = false;
        this.downIcon = true;
        this.commentAddedFlag = true;
        this.category = 'Category';
        this.inputTag = true;
        this.spamModal = false;
        this.start = 0;
        this.check = 0;
        this.showTextbox();

        // start timer for timestamp
        this.startCount();

        // Abuse modal radio button data
        this.firstReason = this.constants.FIRTSTREASON;
        this.secondReason = this.constants.SECONDREASON;
        this.thirdReason = this.constants.THIRDREASON;
        this.forthReason = this.constants.FOURTHREASON;

        // Skip comment and show more
        this.commentListOfIdea = {
            skipCommentsItem: 0,
            commentsPerPage: 6,
        };

        // filter user default
        this.usersPage = {
            skipPage: 0,
            perPageIdea: 6,
            FilterPage: 'createdAt',
            ideaOrder: 'descending',
            sortByTitle: '',
            sortByAuthor: '',
            sortByTags: [],
            toDate: this.toDate,
            fromDate: this.fromDate
        };

        // Set from and to date
        this.fromDate = utility.getDatewithoutTimstamp(utility.getXMonthsAgoDate(new Date(), 180));
        this.toDate = utility.getDatewithoutTimstamp(new Date());

        // conver date into DD/MM/YYYY format

        let fromDate:any;
        fromDate = this.fromDate.split("/");

        //From month
        if (fromDate[0] < 10) {
            fromDate[0] = 0 + '' + fromDate[0];
        }

        // From day
        if (fromDate[1] < 10) {
            fromDate[1] = 0 + '' + fromDate[1];
        }
        this.fromDate = fromDate[1] + '/' + fromDate[0] + '/' + fromDate[2];

        let toDate:any;
        toDate = this.toDate.split("/");

        // To month
        if (toDate[0] < 10) {
            toDate[0] = 0 + '' + toDate[0];
        }

        //To day
        if (toDate[1] < 10) {
            toDate[1] = 0 + '' + toDate[1];
        }
        this.toDate = toDate[1] + '/' + toDate[0] + '/' + toDate[2];


        this.usersPage.skipPage = 1;
        let todayDate = new Date();

        // Pass data to datepicker
        this.myDatePickerOptions = {
            todayBtnTxt: 'Today',
            dateFormat: 'dd/mm/yyyy',
            firstDayOfWeek: 'mo',
            sunHighlight: true,
            height: '34px',
            width: '260px',
            inline: false,
            disableSince: {
                year: todayDate.getFullYear(),
                month: todayDate.getUTCMonth() + 1, day: todayDate.getDate() + 1
            },
            selectionTxtFontSize: '16px'
        };
        this.getUserLists();
    }

    // pagination click on number
    public pageChanged(event:any):void {
        this.itemPerPage = event.itemsPerPage;
        this.usersPage.skipPage = event.page;
        this.getUserLists();
    };

    // Function call when we change from date
    onFromDateChanged(event:any) {
        // this.fromDate = event.formatted;
        if (event.formatted === '') {

        } else {
            let day, month;
            day = event.date.day;
            month = event.date.month;
            if (event.date.month < 10) {
                month = 0 + '' + event.date.month;
            }
            if (event.date.day < 10) {
                day = 0 + '' + event.date.day;
            }

            this.fromDate = day + '/' + month + '/' + event.date.year;
        }
    }

    // Function call when we change to date
    onToDateChanged(event:any) {
        // this.toDate = event.formatted;
        if (event.formatted === '') {

        } else {
            let day, month;
            day = event.date.day;
            month = event.date.month;
            if (event.date.month < 10) {
                month = 0 + '' + event.date.month;
            }
            if (event.date.day < 10) {
                day = 0 + '' + event.date.day;
            }
            this.toDate = day + '/' + month + '/' + event.date.year;
        }
    }

    // Sort user list of data on click sorted by functionality
    public userListFilter(type, value) {
        // sort name and date icon show hide
        if (type === 'createdAt') {
            this.userName = false;
            this.date = true;
        } else {
            this.userName = true;
            this.date = false;
        }
        this.usersPage.FilterPage = type;
        this.usersPage.ideaOrder = value;
        this.usersPage.skipPage = 1;
        this.listOfUsers = [];
        this.listOfUsersTemplate = [];
        this.getUserLists();
    }

    // Function for search and sort the users
    public getUserLists() {
        this.spinner.showProgress();
        let inputData = {};
        inputData = {
            searchParameter: this.category,
            searchValue: this.searchType,
            skipItem: ((this.usersPage.skipPage - 1) * (this.itemPerPage)),
            itemsperPage: this.itemPerPage,
            sortParameter: this.usersPage.FilterPage,
            sortOrder: this.usersPage.ideaOrder,
            sortByName: this.usersPage.sortByName,
            sortByStatus: this.usersPage.sortByStatus,
            toDate: this.toDate,
            fromDate: this.fromDate
        };
        this.userService.getAbuseData(inputData).subscribe(
            data => this.userSucess(data),
            error => this.userFailure(error));
    }

    // Function call when user abuse success
    private userSucess(stats) {

        this.spinner.hideProgress();

        if (stats.abuseList.length > 0) {
            this.allusers = stats.abuseList;
            this.totalItem = stats.abuseCount;
            this.noContent = true;
        } else {
            this.noContent = true;
        }
    }

    // Function call abuse table set date format
    public formateDate(dates):any {
        return this.utility.getFormattedDateForTree(dates);
    }

    // Function call when user abuse fail
    private userFailure(error) {
        this.spinner.hideProgress();
    }

    // open status and admin update modal
    public openUserModal(user, checkState) {
        this.userModal = true;
        this.updateUser = user;
        if (checkState) {
            this.checkedStatus = user;
            this.checkedStatus.state = checkState;
        } else {
            this.checkedStatus = user;
            this.checkedStatus.state = checkState;
        }
    }

    // close status dialog box
    public closeUserModal() {
        this.userModal = false;
        this.getUserLists();
    }

    // Added fuction for check and uncheck status and admin.
    public activateUser() {
        this.userModal = false;
        this.userService.updateStatus(this.checkedStatus).subscribe(
            data => this.updateUserSucess(data),
            error => this.updateUserFailure(error));
    }

    // Added fuction for check and uncheck status success
    private updateUserSucess(stats) {
        this.userModal = false;
        this.spinner.hideProgress();
        toastr.success('Status Update successfully');
    }

    // Added fuction for check and uncheck status failure
    private updateUserFailure(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);
    }

    // Function for show peofile
    private viewProfile(id) {
        this.profile.hideEdit();
        this.profile.resetProile();
        this.profile.getUserProfileData(id, undefined, undefined);
    }

    // search dropdown function show hide text box
    private showTextbox() {
        if (this.category === 'Title' || this.category === 'User' || this.category === 'Reason') {
            this.searchType = '';
            this.selectTag = false;
            this.inputTag = true;
        } else {
            this.inputTag = false;
            this.selectTag = true;
            this.searchType = 'Search by Category';
        }
    }

    // Function for get idea's id
    private getIdeaIdForAbuse(idea) {
        let input = {
            ideaId: idea.idea,
            userId: idea.user
        };

        this.ideaService.getIdeaIdForAbuse(input).subscribe(
            data => this.getIdeaByIdSucess(data),
            error => this.getIdeaByIdFailure(error));
    }

    // Function for get idea's id success
    private getIdeaByIdSucess(stats) {
        this.spinner.hideProgress();
        this.getIdeaComments(stats);
    }

    // Function for get idea's id fail
    private getIdeaByIdFailure(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);
    }

    // Function for get comment for idea
    public getIdeaComments(evt) {
        let cardData = {
            'ideaId': evt._id,
            'skipItem': this.commentListOfIdea.skipCommentsItem,
            'itemsperPage': this.commentListOfIdea.commentsPerPage,
            'sortParameter': 'createdAt',
            'sortOrder': 'descending'
        };
        this.ideaService.getcardComment(cardData).subscribe(
            data => this.getcommentsuccess(data, evt),
            error => this.getcommentfail(error)
        );

    }

    // Function call if comment success
    public getcommentsuccess(data, evt) {
        this.spinner.hideProgress();
        let ModalData = evt;
        ModalData[0].data = data;
        this.viewDetailIdea = ModalData[0];
        this.ViewDetailIdeaModel.open();
    }

    // Function call if comment fail
    public getcommentfail(data) {
        this.spinner.hideProgress();
    }

    // Function for open notification modal and pass data
    getNotificationModal(idea) {
        this.abuseIdea = idea;
        this.abuseModal.open();

    }

    // Function for call parent profile modal
    notifyParenttoProfileModal(evt) {
        this.userprofile.hideEdit();
        this.userprofile.resetProile();
        this.userprofile.getUserProfileData(evt.user);
        this.UserProfileModal.open();
    }

    // Function for get data for show all spam
    public getDataForSpam(data) {
        this.spamModal = true;
        this.spamReason = '';
        this.allSpam = data;
    }

    // Function for close spam modal window
    public closeSpamForm() {
        this.spamModal = false;
        this.getUserLists();
    }

    // Function for set spam status Approved or Rejected
    public setSpamDataForIdea() {
        this.spamResult = this.allSpam.spam;
        if (this.spamResult) {
            this.spamResult = 'Rejected';
        } else {
            this.spamResult = 'Approved';
        }

        let input = {
            abuseId: this.allSpam._id,
            status: this.spamResult,
            adminReason: this.spamReason
        };
        this.ideaService.getSpamStatus(input).subscribe(
            data => this.getSpamSuccess(data),
            error => this.getSpamFail(error));
    }

    // To function for spam success
    private getSpamSuccess(data) {
        this.spinner.hideProgress();
        toastr.success('Spam Update successfully');
        this.spamModal = false;
        this.getUserLists();
    }

    // To function for spam fail
    private getSpamFail(error) {
        this.spinner.hideProgress();
        toastr.error(error.error_message);
    }

    // User log for keystroke event
    public onKeyPressAbuse(event) {

        let input = {
            'target': 'HTMLInputElement : ' + event.key + ' abuse search',
            'value': 'abuse search',
            'action': 'keystroke'
        };
        // API call for send user log data
        this.userService.setUserLogs(input).subscribe();
    }

    // To call every 1 sec for count how much time we spent on this page
    public  timedCount() {
        this.start = this.start + 1;
        this.end = setTimeout(() => {
            this.timedCount()
        }, 1);
    }

    // To function for start timstamp count
    public startCount() {
        if (!this.check) {
            this.check = 1;
            this.timedCount();
        }
    }

    // To function for stop timstamp count
    public stopCount() {
        clearTimeout(this.end);
        this.check = 0;
    }

    // To call this function when leave from this controller
    ngOnDestroy() {
        // To stop count function call
        this.stopCount();

      // API call for tract navigation sequence
      let seq = {
        sequence: {
          "pageName": 'admin/abuseList',
          "timeSpent": this.start
        }

      };
      this.userService.setUrlSeq(seq).subscribe();

    }

    // Function call after view for log API
    ngAfterViewChecked() {
        let self = this;
        $('.userTemplate').unbind().mousedown(function (event) {
            self.checkAllLogs(event);
        });
    }

    // Function for check all logs
    public checkAllLogs(event) {
        let self = this;
        let buttons;
        if (event.button === 0) {
            buttons = 'left click';
        } else if (event.button === 1) {
            buttons = 'roller click';
        } else {
            buttons = 'right click';
        }
        let domTarget = event.target;
        let domTargetString = domTarget.toString();
        let stringDemo = domTargetString.substr(12, 25);
        let index = stringDemo.indexOf('E');
        let dom = stringDemo.substr(0, index);
        let text = $(event.target).unbind().text();


        let input = {
            'target': dom + ' ' + text,
            'value': text,
            'action': buttons
        };

        if (event.target.className.indexOf('ng2-smart-page-link page-link') >= 0) {
            let input = {
                'target': 'Pagination',
                'value': '',
                'action': buttons
            };

            self.userService.setUserLogs(input).subscribe();

        } else if (event.target.className === 'btn btn-default btn-auth lgn profileUploadbutton') {
            let data = {
                'target': 'submit',
                'value': 'editProfile',
                'action': 'left click'
            };
            self.userService.setUserLogs(data).subscribe();
        } else {
            self.setUserLogs(input);
        }
    }

    // Function for call API for log
    public setUserLogs(input) {

        this.userService.setUserLogs(input).subscribe();
    }

}
